/**
 *  @(#)  IFAAAuthenticator  module    1.0  2017/03/24
 *
 *  Copyright  (c)  2017,  IFAA  and/or  its  affiliates.  All  rights  reserved.
 *
 *  Redistribution  and  use  in  source  and  binary  forms,  with  or  without
 *  modification,  are  permitted  provided  that  the  following  conditions  are  met:
 *
 *  -Redistribution  of  source  code  must  retain  the  above  copyright  notice,  this
 *    list  of  conditions  and  the  following  disclaimer.
 *
 *  -Redistribution  in  binary  form  must  reproduce  the  above  copyright  notice,
 *    this  list  of  conditions  and  the  following  disclaimer  in  the  documentation
 *    and/or  other  materials  provided  with  the  distribution.
 *
 *  Neither  the  name  of  IFAA  or  the  names  of  contributors  may
 *  be  used  to  endorse  or  promote  products  derived  from  this  software  without
 *  specific  prior  written  permission.
 *
 *  This  software  is  provided  "AS  IS,"  without  a  warranty  of  any  kind.  ALL
 *  EXPRESS  OR  IMPLIED  CONDITIONS,  REPRESENTATIONS  AND  WARRANTIES,  INCLUDING
 *  ANY  IMPLIED  WARRANTY  OF  MERCHANTABILITY,  FITNESS  FOR  A  PARTICULAR  PURPOSE
 *  OR  NON-INFRINGEMENT,  ARE  HEREBY  EXCLUDED.  IFAA,  ORG.
 *  AND  ITS  LICENSORS  SHALL  NOT  BE  LIABLE  FOR  ANY  DAMAGES  SUFFERED  BY  LICENSEE
 *  AS  A  RESULT  OF  USING,  MODIFYING  OR  DISTRIBUTING  THIS  SOFTWARE  OR  ITS
 *  DERIVATIVES.  IN  NO  EVENT  WILL  IFAA  OR  ITS  LICENSORS  BE  LIABLE  FOR  ANY  LOST
 *  REVENUE,  PROFIT  OR  DATA,  OR  FOR  DIRECT,  INDIRECT,  SPECIAL,  CONSEQUENTIAL,
 *  INCIDENTAL  OR  PUNITIVE  DAMAGES,  HOWEVER  CAUSED  AND  REGARDLESS  OF  THE  THEORY
 *  OF  LIABILITY,  ARISING  OUT  OF  THE  USE  OF  OR  INABILITY  TO  USE  THIS  SOFTWARE,
 *  EVEN  IF  IFAA  HAS  BEEN  ADVISED  OF  THE  POSSIBILITY  OF  SUCH  DAMAGES.
 *
 *  You  acknowledge  that  this  software  is  not  designed,  licensed  or  intended
 *  for  use  in  the  design,  construction,  operation  or  maintenance  of  any
 *  nuclear  facility.
 *
 */
package com.ifaa.sdk.api;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.ifaa.sdk.auth.AuthenticatorLOG;

/**
 * 解析指纹及可穿戴设备校验数据<br/>
 * <pre>格式定义
 * {
 *      ai:clientStatus#authType#wearableType#protocalType#protocalVersion#vender#serviceVersion;...
 *      di:deviceid1;deviceid2          // 相同的deviceID以#代替
 *      ap:authParameter1;authParameter2
 *      pm:phoneModel
 * }</pre>
 * @author qiyi.wxc
 */
public class BICDataUtil {

    private final static String AUTHINFO_KEY      = "ai";

    private final static String DEVICEID_KEY      = "di";

    private final static String AUTHPARAMETER_KEY = "ap";

    private final static String PHONEMODEL_KEY    = "pm";

    private final static String SERVICEVERSION_KEY    = "sv";

    private final static String CPMODEL_KEY    = "cm";

    private BICDataUtil() {
    }

    /**
     * 根据JSON数据解析出参数模型
     * @param dataJson
     * @return
     */
    public static List<BICDataModel> fromDataJson(String data) {
        if (data == null || data.trim().equals("")) {
            return null;
        }

        List<BICDataModel> models = new ArrayList<BICDataModel>();

        JSONObject dataJSON = null;
        try {
            dataJSON = new JSONObject(data);
        } catch (JSONException e) {
            AuthenticatorLOG.error("BICDataUtil", e);
        }
        if (dataJSON == null) {
            return null;
        }

        String authInfo = dataJSON.optString(AUTHINFO_KEY);
        String deviceId = dataJSON.optString(DEVICEID_KEY);
        String authParameter = dataJSON.optString(AUTHPARAMETER_KEY);
        String phoneModel = dataJSON.optString(PHONEMODEL_KEY);
        String deviceModel = dataJSON.optString(CPMODEL_KEY);

        if (authInfo == null || authInfo.trim().equals("")) {
            return null;
        }

        String[] authInfoList = authInfo.split(";");
        int listSize = authInfoList.length;

        String[] deviceIdList = { "" };
        String[] authParameterList = { "" };
        String[] phoneModelList = { "" };
        String[] deviceModelList = { "" };

        if (deviceId != null) {
            deviceIdList = deviceId.split(";");
            for (int i = 0; i < deviceIdList.length; i++) {
                if (deviceIdList[i].equals("#")) {
                    deviceIdList[i] = deviceIdList[i - 1];
                }
            }
        }
        if (authParameter != null) {
            authParameterList = authParameter.split(";");
        }
        if (phoneModel != null) {
            phoneModelList = phoneModel.split(";");
        }

        if (deviceModel!= null) {
            deviceModelList = deviceModel.split(";");
        }

        for (int i = 0; i < listSize; i++) {
            BICDataModel model = new BICDataModel(authInfoList[i], deviceIdList[i > deviceIdList.length - 1 ? 0 : i],
                    authParameterList[i > authParameterList.length - 1 ? 0 : i],
                    phoneModelList[i > phoneModelList.length - 1 ? 0 : i],
                    deviceModelList[i > deviceModelList.length - 1 ? 0 : i]
                    );
            models.add(model);
        }

        return models;
    }

    /**
     * 根据模型构造数据
     * @param dataJson
     * @return
     */
    public static String toDataJson(List<BICDataModel> models, Context context) {
        if (models == null || models.size() == 0) {
            return "";
        }

        String ai = "";
        String di = "";
        String ap = "";
        String pm = "";
        String sv = "";
        String cm = "";
        for (BICDataModel model : models) {
            // append auth info
            if (!ai.equals("")) {
                ai += ";";
            }
            ai += model.getAuthInfo();

            // append deviceid
            if (di.equals("")) {
                di += model.getDeviceId();
            } else if (!di.endsWith(model.getDeviceId())) {
                di += ";" + model.getDeviceId();
            } else if (di.endsWith(model.getDeviceId())) {
                di += ";" + "#";
            }

            // append phoneModel
            if (pm.equals("")) {
                pm += model.getPhoneModel();
            }

            if (cm.equals("")) {
                cm += model.getDeviceModel();
            }
        }
        JSONObject dataJson = new JSONObject();
        try {
            dataJson.put(AUTHINFO_KEY, ai);
            dataJson.put(DEVICEID_KEY, di);
            dataJson.put(AUTHPARAMETER_KEY, ap);
            dataJson.put(PHONEMODEL_KEY, pm);
            dataJson.put(SERVICEVERSION_KEY, sv);
            dataJson.put(CPMODEL_KEY, cm);
        } catch (JSONException e) {
            // do nothing
        }
        return dataJson.toString();
    }
}
